<?php
namespace App\Http\Controllers\Admin;

use App\Models\Picture;

/**
 * 文件控制器
 * 主要用于下载模型的文件上传和下载
 */
class FileController extends BaseController
{

    public function __construct(Picture $picture)
    {
        $this->picture = $picture;
    }

    /* 文件上传 */
    public function upload()
    {
        $return = ['status' => 1, 'info' => '上传成功', 'data' => ''];
        /* 调用文件上传组件上传文件 */
        $File = D('File');
        $file_driver = C('DOWNLOAD_UPLOAD_DRIVER');
        $info = $File->upload(
            $_FILES,
            C('DOWNLOAD_UPLOAD'),
            C('DOWNLOAD_UPLOAD_DRIVER'),
            C("UPLOAD_{$file_driver}_CONFIG")
        );

        /* 记录附件信息 */
        if ($info) {
            $return['data'] = think_encrypt(json_encode($info['download']));
            $return['info'] = $info['download']['name'];
        } else {
            $return['status'] = 0;
            $return['info'] = $File->getError();
        }

        return $this->ajaxReturn($return);
    }

    /* 下载文件 */
    public function download($id = null)
    {
        if (empty($id) || !is_numeric($id)) {
            $this->error('参数错误！');
        }

        $logic = D('Download', 'Logic');
        if (!$logic->download($id)) {
            $this->error($logic->getError());
        }

    }

    /**
     * 上传图片
     */
    public function postUploadPicture()
    {
        /* 返回标准数据 */
        $return = ['status' => 1, 'info' => '上传成功', 'data' => ''];
        if (!is_login()) {
            return ['status' => 0, 'info' => '请登录后在操作'];
        }
        //获取上传配置
        $uploadConfig = config('upload.PICTURE_UPLOAD');
        $uploadConfig['rootPath'] = public_path().$uploadConfig['rootPath'].request('shop_id').'/';
        if (!is_dir($uploadConfig['rootPath'])) {
            if(!mkdir($uploadConfig['rootPath'],0755)) {
                return ['status' => 0, 'info' => '该上传目录创建失败'];
            }
        }
        //设置上传驱动
        $driver = config('upload.PICTURE_UPLOAD_DRIVER');
        //获取上传驱动配置
        $driverConfig = config("upload.UPLOAD_{$driver}_CONFIG");
        $info = $this->picture->upload($_FILES, $uploadConfig, $driver, $driverConfig);
        /* 记录图片信息 */
        if ($info) {
            $return['status'] = 1;
            $return = array_merge($info['download'], $return);
        } else {
            $return['status'] = 0;
            $return['info'] = $this->picture->getError();
        }
        /* 返回JSON数据 */
        return $this->ajaxReturn($return);
    }
}
